package com.nmc.webapp.action;


import java.util.ArrayList;
import java.util.List;

import org.springframework.dao.DataIntegrityViolationException;

import com.nmc.common.Constants;
import com.nmc.common.HospitalStatusEnum;
import com.nmc.common.UserTypeEnum;
import com.nmc.service.manager.BirthManager;
import com.nmc.service.manager.HospitalManager;
import com.nmc.service.manager.UserExistsException;
import com.nmc.service.manager.ZonesManager;
import com.nmc.service.model.Birth;
import com.nmc.service.model.Hospital;
import com.nmc.service.model.LabelValue;
import com.nmc.service.model.User;
import com.nmc.service.model.Zones;
import com.nmc.webapp.util.RequestUtil;
import com.nmc.webapp.util.Util;

/**
 * Action to allow new users to sign up.
 */
public class HospitalAction extends BaseAction {
    private static final long serialVersionUID = 6558317334878272308L;
    private Hospital hospital;
    private String cancel;
    private HospitalManager hospitalManager;
    private ZonesManager zonesManager;
    private List<Zones> zones = null;
    private List<Hospital> hospitalList;
    private String query;
    private List<LabelValue> statusList ;
    private String id;
    private List<Birth> birthList;
    private String updatedStatus;
    private int zoneId = -1;
    private BirthManager birthManager;
	private List<Zones> zoneList;
    
    
    
    public BirthManager getBirthManager() {
		return birthManager;
	}


	public void setBirthManager(BirthManager birthManager) {
		this.birthManager = birthManager;
	}


	public List<Birth> getBirthList() {
		return birthList;
	}


	public void setBirthList(List<Birth> birthList) {
		this.birthList = birthList;
	}


	public String getId() {
		return id;
	}


	public void setId(String id) {
		this.id = id;
	}


	public void setCancel(String cancel) {
        this.cancel = cancel;
    }

	public String cancel() {
		 
//	    if ("list".equals(from)){
//	    	return "cancel";
//        }
        
        return "cancel";
    }

    /**
     * When method=GET, "input" is returned. Otherwise, "success" is returned.
     * @return cancel, input or success
     */
    public String regHospital() {
        
        return SUCCESS;
    }
    
    /**
     * When method=GET, "input" is returned. Otherwise, "success" is returned.
     * @return cancel, input or success
     */
    public String editHospital() {
    	hospital = hospitalManager.get(Long.parseLong(id));
        return SUCCESS;
    }

    /**
     * Returns "input"
     * @return "input" by default
     */
    public String doDefault() {
        return INPUT;
    }
    
    public String searchForm(){
    	
    	return SUCCESS;
    }

    
    public String save(){
    	
    	User user = new User();
    	String password =  Util.randomAlphanumeric(Constants.RANDOM_COUNT);
    	try {
    		
//    		Zones zones = new Zones();
//    		zones.setId(1); 
//    		hospital.setZones(zones);
        	hospital = hospitalManager.save(hospital);
        	
        	user.setFirstName(hospital.getName());
	    	user.setLastName(hospital.getContactPersonName());
	    	user.setAddress(hospital.getAddress());
	    	user.setUsername(hospital.getEmail());
	    	user.setPassword(password);
	    	user.setEmail(hospital.getEmail());
	    	user.addRole(roleManager.getRole(Constants.HOSPITAL_ROLE));
	    	user.setEnabled(true);
    	    user.setHospital(hospital);
    	    user.setUserType(UserTypeEnum.Hospital.name());
			user = userManager.saveUser(user);
		
	
    	} catch (UserExistsException e) {
			e.printStackTrace();
			  List<Object> args = new ArrayList<Object>();
			    args.add(user.getUsername());
	            args.add(user.getEmail());
	            addActionError(getText("errors.existing.user", args));
	            return INPUT;
		}catch(DataIntegrityViolationException e){ 
			e.printStackTrace();
			addActionError(getText("hospital.errors.email.already.exists" ));
			return INPUT;
    	}catch(Exception e){
			e.printStackTrace();
			addActionError(getText("hospital.errors.registration.failed" ));
			return INPUT;
		}
		try {
			List<Object> args = new ArrayList<Object>();
			args.add(user.getFullName());
			user.setConfirmPassword(password);
			mailMessage
					.setSubject(getText("hospital.registration.email.subject"));
			if(templateName == null){
				templateName = "accountCreated.vm";
			}
			sendUserMessage(user, getText("newuser.email.message", args),
					RequestUtil.getAppURL(getRequest()));
		} catch (Exception me) {
			me.printStackTrace();
		}
		 saveMessage(getText("hospital.created.message"));
		 hospital = new Hospital();
    	return SUCCESS;
    }
    
    public String updateStatus(){
    	try {
    		hospital = hospitalManager.get(Long.parseLong(id));
    		hospital.setStatus(updatedStatus);
    		hospitalManager.save(hospital);
    		
    	} catch (Exception e){
    		e.printStackTrace();
    		return "error";
    	}
    	 saveMessage(getText("hospital.updated.message"));
    	return SUCCESS;
    }
    public String list(){
    	if(zoneId == -1){
    		zoneId = userManager.getUserByUsername(getRequest().getRemoteUser()).getZoneId();
    	}
    	hospitalList = hospitalManager.searchHospital(zoneId, query);
    	return SUCCESS;
    }
    
    public String birthList() {
    	try{
    		birthList = birthManager.getHospitalBirthList(Integer.parseInt(id));
    	}catch (Exception e) {
    		System.out.println("Error " + e.getMessage());
    		return ERROR;
    	}
    	return SUCCESS;
    	
    }
    
    public List<Hospital> getHospitalList() {
    	
    	return hospitalList;
    	
    }
    
	public void setHospital(Hospital hospital) {
		this.hospital = hospital;
	}


	public Hospital getHospital() {
		return hospital;
	}


	public void setHospitalManager(HospitalManager hospitalManager) {
		this.hospitalManager = hospitalManager;
	}


	public HospitalManager getHospitalManager() {
		return hospitalManager;
	}


	public void setZonesManager(ZonesManager zonesManager) {
		this.zonesManager = zonesManager;
	}


	public ZonesManager getZonesManager() {
		return zonesManager;
	}


	public void setZones(List<Zones> zones) {
		this.zones = zones;
	}


	public List<Zones> getZones() {
		if(zones == null){
			zones = zonesManager.getZoness();
		}
		return zones;
	}


	public void setHospitalList(List<Hospital> hospitalList) {
		this.hospitalList = hospitalList;
	}


	public String hospitalList() {
		
		try{
			hospitalList = hospitalManager.getAll();
    	}catch (Exception e) {
    		System.out.println("Error " + e.getMessage());
    		return ERROR;
    	}
    	return SUCCESS;
		//return hospitalList;
	}
	
	public String zonesList() {
		
		try{
			zoneList = zonesManager.getAll();
    	}catch (Exception e) {
    		System.out.println("Error " + e.getMessage());
    		return ERROR;
    	}
    	return SUCCESS;
		//return hospitalList;
	}

	/**
	 * @return the zoneList
	 */
	public List<Zones> getZoneList() {
		return zoneList;
	}


	/**
	 * @param zoneList the zoneList to set
	 */
	public void setZoneList(List<Zones> zoneList) {
		this.zoneList = zoneList;
	}


	public void setQ(String q) {
        this.query = q;
    }


	public void setStatusList(List<LabelValue> statusList) {
		this.statusList = statusList;
	}


	public List<LabelValue> getStatusList() {
		if(statusList == null){
    		statusList = new ArrayList<LabelValue>();
    		LabelValue labelValue = new LabelValue(HospitalStatusEnum.OnHold.name(),HospitalStatusEnum.OnHold.name());
    		statusList.add(labelValue);
    		labelValue = new LabelValue(HospitalStatusEnum.Suspended.name(),HospitalStatusEnum.Suspended.name());
    		statusList.add(labelValue);
    		labelValue = new LabelValue(HospitalStatusEnum.Registered.name(),HospitalStatusEnum.Registered.name());
    		statusList.add(labelValue);
    		
    	}
		return statusList;
	}


	public String getUpdatedStatus() {
		return updatedStatus;
	}


	public void setUpdatedStatus(String updatedStatus) {
		this.updatedStatus = updatedStatus;
	}


	public void setZoneId(int zoneId) {
		this.zoneId = zoneId;
	}


	public int getZoneId() {
		return zoneId;
	}
	
}
